package com.hfmall.controller;


import com.hfmall.entity.HfAddress;
import com.hfmall.entity.HfUser;
import com.hfmall.entity.ResponseCode;
import com.hfmall.service.IHfAddressService;
import com.hfmall.utils.ResponseState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liclo
 * @since 2021-08-12
 */
@RestController
@RequestMapping("/address")
public class HfAddressController {

    @Autowired
    private IHfAddressService addressService;
    @PostMapping("getAll")
    public ResponseCode<List<HfAddress>> getByUser(@RequestBody HfUser user){
        //从session中获取 user
        if (user==null){
            return new ResponseCode<>(ResponseState.FAIL, "fail");
        }
           List<HfAddress> addresses = addressService.getByUser(user.getId());
           return new ResponseCode<>(addresses);

    }

    @GetMapping("getById/{id}")
    public ResponseCode<HfAddress> getById(@PathVariable int id){

        return new ResponseCode<>( addressService.getById(id));
    }

    @PostMapping("update")
    public ResponseCode<?> update(@RequestBody HfAddress address){

        addressService.update(address);
        return new ResponseCode<>(ResponseState.SUCCESS);
    }

    @PostMapping("add")
    public ResponseCode<HfAddress> add(@RequestBody HfAddress address){
        System.out.println(address.getUserId());
        addressService.add(address);


        return new ResponseCode<>(addressService.getById(address.getId()));
    }

    @PostMapping("setDefault/{id}")
    public ResponseCode<?> setDefault(@PathVariable int id,@RequestBody HfUser user){
        if (user==null){
            return new ResponseCode<>(ResponseState.FAIL, "fail");
        }

        addressService.setDefault(id,user.getId());
        return new ResponseCode<>(ResponseState.SUCCESS);
    }

    @GetMapping("del/{id}")
    public ResponseCode<?> delete(@PathVariable int id){

        addressService.removeById(id);
        return new ResponseCode<>(ResponseState.SUCCESS);
    }
}
